package com.example.oss.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.oss.entity.Course;
import com.example.oss.entity.Order;
import com.example.oss.exception.VersionException;
import com.example.oss.mapper.CourseMapper;
import com.example.oss.mapper.OrderMapper;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class OrderService {

    @Resource
    private CourseMapper courseMapper;
    @Resource
    private OrderMapper orderMapper;



    /**
     * 下单
     *
     * @param courseId
     * @param stuId
     * @return
     */
    @Transactional
    @Retryable(value = {VersionException.class}, maxAttempts = 3)
    public Order order(int courseId, int stuId) {

        //减库存
        Course course = courseMapper.selectAmount(courseId);
        course.setAmount(course.getAmount() - 1);
        int row = courseMapper.reduceAmount(course);

        //减库存失败
        if (row == 0) {
            throw new VersionException("产生减库存异常！");
        } else {
            //新增订单
            Order order = new Order();
            order.setCourseId(courseId);
            order.setStuId(stuId);
            int insertResult = orderMapper.insertOrder(order);
            if (insertResult == 1) {  //新增成功
                return order;
            }
        }

        return null;
    }


    public Order getOrderByStuIdFromDB(int stuId) {
        return orderMapper.selectOne(new QueryWrapper<Order>().eq("stu_id", stuId));
    }
    public Boolean existStuId(int stuId) {
        return orderMapper.existStuId(stuId) != null;
    }
    public void deleteOrderByStuId(int stuId) {
        orderMapper.delete(new QueryWrapper<Order>().eq("stu_id", stuId));
    }
}
